package com.lzy.wzy.controller;

import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.ui.modeler.domain.Model;
import org.flowable.ui.modeler.model.ModelRepresentation;
import org.flowable.ui.modeler.service.FlowableModelQueryService;
import org.flowable.ui.modeler.serviceapi.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/login")
@Slf4j
public class TestController {

    @Autowired
    private ModelService modelService;
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private FlowableModelQueryService flowableModelQueryService;

    //加入流程
    @RequestMapping("/test")
    @ResponseBody
    public String deploy(String id) {
        try {
            Model model = modelService.getModel(id.trim());
            //到时候需要添加分类
            String categoryCode = "1000";
            BpmnModel bpmnModel = modelService.getBpmnModel(model);
            //添加隔离信息
            String tenantId = "flow";
            //必须指定文件后缀名否则部署不成功
            Deployment deploy = repositoryService.createDeployment()
                    .name(model.getName())
                    .key(model.getKey())
                    .category(categoryCode)
//                    .tenantId(tenantId)
                    .addBpmnModel(model.getKey() + ".bpmn", bpmnModel)
                    .deploy();
            return deploy.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //导入模板
    @RequestMapping(value = "/importModel", method = RequestMethod.POST)
    @ResponseBody
    public String importModel(HttpServletRequest request, @RequestParam("static/file") MultipartFile file) {
        ModelRepresentation modelRepresentation = new ModelRepresentation();
        modelRepresentation.setTenantId("flow");
        ModelRepresentation processModel = flowableModelQueryService.importProcessModel(request, file);
        System.out.println(processModel.getId());
        return "ok";
    }

    public void bf(HttpServletResponse response){
        response.reset();
    }

}
